import { S, U, getRequestId, mapField } from '../../lib/backend'
import Q from 'q'
import axios from 'axios'
import envFuncs from '@/config/base'
let env = envFuncs.getParams()

export default {
  // 获取sms
  sendSmsCode ({ commit }, info) {
    const params = JSON.stringify(info)
    return Q.promise((resolve, error) => {
      axios.post(
        env.CRM_API_HOST + '/send_smscode',
        params
      ).then((response) => {
        if (response.data.errcode === 0) {
          resolve(response.data)
        } else {
          error(response.data)
        }
      }).catch((e) => {
        console.log(e.message)
        const msg = '系统错误...请联系管理员...'
        error({
          errcode: -1,
          errmsg: msg,
          data: []
        })
      })
    })
  },
  verifySmscode ({ commit, rootState }, info) {
    const params = JSON.stringify(info)
    return Q.promise((resolve, error) => {
      axios.post(
        env.CRM_API_HOST + '/users/' + rootState.app.token + '/verify_smscode',
        params
      ).then((response) => {
        if (response.data.errcode === 0) {
          resolve(response.data)
        } else {
          resolve(response.data)
        }
      }).catch((e) => {
        console.log(e.message)
        const msg = '系统错误...请联系管理员...'
        error({
          errcode: -1,
          errmsg: msg,
          data: []
        })
      })
    })
  },
  // 保存sms
  saveSmsInfo ({ dispatch, commit, state, rootState }, info) {
    const params = JSON.stringify({
      info: {
        is_open_sms: info.is_open_sms,
        CRM_sign: info.CRM_sign
      },
      trace: {
        requestId: getRequestId()
      }
    })
    return Q.Promise((success, error) => {
      axios.post(
        env.CRM_API_HOST + '/sites/' + rootState.auth.site_id + '/CRM_info',
        params,
        { headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }}
      ).then((response) => {
        if (response.data.results) {
          const smsInfo = response.data.results
          response.data.results.data = smsInfo
        }
        success(response)
      }).catch((err) => {
        error(err)
        console.log(err)
      })
    })
  }
}
